package com.ws.lv.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.lv.bean.Acl_user;
import com.ws.lv.bean.Order_info;
import com.ws.lv.bean.Save;
import com.ws.lv.bean.User;
import com.ws.lv.service.Order_infoService;
import com.ws.lv.service.RouteService;
import com.ws.lv.service.SaveService;
import com.ws.lv.service.UserService;
import com.ws.lv.util.Res;
import com.ws.lv.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    SaveService saveService;
    @Autowired
    Order_infoService order_infoService;
    @Autowired
    private RouteService routeService;

    //增加前台用户(注册)
    @RequestMapping("/userRegister")
    public String userRegister(User user, MultipartFile image) {
        System.out.println("增加前台用户 注册");
        try {
            User u = userService.selectUserByUser_name(user.getUser_name());
            if (u==null){
                if (image.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = image.getOriginalFilename().split("\\.")[1];
                    user.setUser_tx(uuid+"."+suffix);
                    user.setUser_pass(SecurityUtils.encrypt(user.getUser_pass()));
                    image.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                    int i = userService.insertUser(user);
                    return "redirect:/homepage/toHomeLogin";
                }
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/homepage/toRegister";
    }

    //前端登录功能
    @RequestMapping("/homeLogin")
    public String homeLogin(User user, HttpServletRequest request){
        System.out.println("前端登录功能");
        User u = userService.selectUserByUser_name(user.getUser_name());
        System.out.println(u+"----------------");
        if (u!=null){
            boolean verify = SecurityUtils.verify(user.getUser_pass(),u.getUser_pass());
            if (verify){
                request.getSession().setAttribute("u",u);
                return "forward:/homepage/toHomePage";
            }
        }
        return "redirect:/homepage/toHomeLogin";
    }

    //前台页面退出登录功能
    @RequestMapping("/outLogin")
    public String outLogin(HttpServletRequest request){
        System.out.println("退出登录");
        request.getSession().removeAttribute("u");
        return "redirect:/homepage/toHomePage";
    }

    //前台页面切换账号功能
    @RequestMapping("/qiehuan")
    public String qiehuan(HttpServletRequest request){
        System.out.println("切换账号");
        request.getSession().removeAttribute("u");
        return "redirect:/homepage/toHomeLogin";
    }

    //查询用户信息
    @RequestMapping("/selectUsers")
    public String selectUsers(String user_name, String user_phone, HttpServletRequest request, Integer currentPage, Model model){
        System.out.println("查询用户信息");
        PageHelper pageHelper = new PageHelper();//分页帮助类
        if (currentPage == null){
            pageHelper.startPage(1, 5);
        }else {
            pageHelper.startPage(currentPage, 5);
        }
        List<User> users = userService.selectUsers(user_name, user_phone);
        PageInfo pageInfo = new PageInfo(users);
        model.addAttribute("pageInfo", pageInfo);
        request.setAttribute("user_name",user_name);
        request.setAttribute("user_phone",user_phone);
        return "adminpage/user/list";
    }

    //去添加页面
    @RequestMapping("/toInsertUser")
    public String toInsertUser(){
        System.out.println("去添加页面");
        return "adminpage/user/add";
    }

    //添加用户
    @RequestMapping("/insertUser")
    public String insertUser(User user, MultipartFile image) {
        System.out.println("增加用户");
        try {
            User u = userService.selectUserByUser_name(user.getUser_name());
            if (u==null){
                if (image.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = image.getOriginalFilename().split("\\.")[1];
                    user.setUser_tx(uuid+"."+suffix);
                    user.setUser_pass(SecurityUtils.encrypt(user.getUser_pass()));
                    image.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                    int i = userService.insertUser(user);
                }
            }else {
                return "redirect:/user/toInsertUser";
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/user/selectUsers";
    }

    //去修改用户页面
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(int user_id, Model model){
        System.out.println("去修改用户页面");
        User user = userService.selectUserByUser_id(user_id);
        model.addAttribute("user",user);
        return "adminpage/user/update";
    }
    
    //修改用户信息
    @RequestMapping("/updateUser")
    public String updateUser(User user, MultipartFile image,String oldUser_tx) {
        System.out.println("修改用户信息");
        try {
            User newUser = userService.selectUserByUser_name(user.getUser_name());
            if (newUser==null){
                if (image.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = image.getOriginalFilename().split("\\.")[1];
                    user.setUser_tx(uuid+"."+suffix);
                    System.out.println("更换新头像");
                    image.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                    File file = new File(Res.homeTxFileDir+oldUser_tx);
                    if (file.exists()){
                        file.delete();
                        System.out.println("删除原头像");
                    }
                }else {
                    System.out.println("使用原头像");
                    user.setUser_tx(oldUser_tx);
                }
            }else {
                if (newUser.getUser_id() == user.getUser_id()){
                    if (image.getSize() > 0){
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        String suffix = image.getOriginalFilename().split("\\.")[1];
                        user.setUser_tx(uuid+"."+suffix);
                        System.out.println("更换新头像2");
                        image.transferTo(new File(Res.homeTxFileDir+uuid+"."+suffix));
                        File file = new File(Res.homeTxFileDir+oldUser_tx);
                        if (file.exists()){
                            file.delete();
                            System.out.println("删除原头像");
                        }
                    }else {
                        System.out.println("使用原头像2");
                        user.setUser_tx(oldUser_tx);
                    }
                }else {
                    return "redirect:/user/toUpdateUser?user_id="+user.getUser_id();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        int i = userService.updateUser(user);
        return "redirect:/user/selectUsers";
    }

    //去修改用户密码页面
    @RequestMapping("/toUpdateUserPassword")
    public String toUpdateUserPassword(int user_id, Model model){
        System.out.println("去修改用户密码页面");
        model.addAttribute("user_id",user_id);
        return "adminpage/user/updatePassword";
    }

    //修改用户密码
    @RequestMapping("/updateUserPass")
    public String updateUserPass(int user_id, String oldPassword, String newPassword){
        System.out.println("修改用户密码");
        User user = userService.selectUserByUser_id(user_id);
        boolean verify = SecurityUtils.verify(oldPassword,user.getUser_pass());
        if (verify){
            String newPass = SecurityUtils.encrypt(newPassword);
            int i = userService.updateUserPass(newPass,user_id);
        }else {
            return "redirect:/user/toUpdateUserPassword?user_id="+user_id;
        }
        return "redirect:/user/selectUsers";
    }

    @RequestMapping("/deleteUsers")
    public String deleteUsers(String userIds){
        System.out.println("删除多个用户");
        String[] split = userIds.split(",");
        ArrayList<Integer> user_id = new ArrayList<>();
        for (String s : split) {
            user_id.add(Integer.parseInt(s));
        }
        for (Integer id : user_id){
            User user = userService.selectUserByUser_id(id);
            File file = new File(Res.homeTxFileDir+user.getUser_tx());
            if (file.exists()){
                file.delete();
            }
            //删除有关的订单
            order_infoService.deleteOrder_infoByUserId(id);
            //删除有关的收藏 和 修改线路数量
            List<Save> saves = saveService.selectSavesByUserId(id);
            for (Save save : saves) {
                Integer routeId = save.getRoute().getRoute_id();
                routeService.updateRouteSaveNumberMinus(routeId);
            }
            saveService.deleteSaveByUserId(id);
        }
        int i = userService.deleteUsers(user_id);
        return "redirect:/user/selectUsers";
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(int user_id){
        System.out.println("删除一个用户");
        User user = userService.selectUserByUser_id(user_id);
        File file = new File(Res.homeTxFileDir+user.getUser_tx());
        if (file.exists()){
            file.delete();
        }
        //删除有关的订单
        order_infoService.deleteOrder_infoByUserId(user_id);
        //删除有关的收藏 和 修改线路数量
        List<Save> saves = saveService.selectSavesByUserId(user_id);
        for (Save save : saves) {
            Integer routeId = save.getRoute().getRoute_id();
            routeService.updateRouteSaveNumberMinus(routeId);
        }
        saveService.deleteSaveByUserId(user_id);

        int i = userService.deleteUser(user_id);
        return "redirect:/user/selectUsers";
    }

    @RequestMapping("/zhuxiao")
    public String zhuxiao(HttpServletRequest request){
        User u = (User) request.getSession().getAttribute("u");
        System.out.println("注销用户");
        User user = userService.selectUserByUser_id(u.getUser_id());
        File file = new File(Res.homeTxFileDir+user.getUser_tx());
        if (file.exists()){
            file.delete();
        }
        //删除有关的订单
        order_infoService.deleteOrder_infoByUserId(u.getUser_id());
        //删除有关的收藏 和 修改线路数量
        List<Save> saves = saveService.selectSavesByUserId(u.getUser_id());
        for (Save save : saves) {
            Integer routeId = save.getRoute().getRoute_id();
            routeService.updateRouteSaveNumberMinus(routeId);
        }
        saveService.deleteSaveByUserId(u.getUser_id());

        int i = userService.deleteUser(u.getUser_id());
        return "redirect:/user/qiehuan";
    }






}
